import { useTemplateRef } from 'vue';
import type { FormInst, FormValidationError } from 'naive-ui';
import { REG_CODE_SIX, REG_EMAIL, REG_PHONE, REG_PWD, REG_USER_NAME } from '@/constants/reg';
import * as customRules from './custom-rules'; /** 自定义校验规则 */

export function useFormRules() {
  const patternRules = {
    userName: {
      pattern: REG_USER_NAME,
      message: '用户名格式不正确',
      trigger: 'blur'
    },
    phone: {
      pattern: REG_PHONE,
      message: '手机号格式不正确',
      trigger: 'blur'
    },
    pwd: {
      pattern: REG_PWD,
      message: '密码格式不正确，6-18位字符，包含字母、数字、下划线',
      trigger: 'blur'
    },
    code: {
      pattern: REG_CODE_SIX,
      message: '请输入6位验证码',
      trigger: 'blur'
    },
    email: {
      pattern: REG_EMAIL,
      message: '邮箱格式不正确',
      trigger: 'blur'
    }
  } satisfies Record<string, App.Global.FormRule>;

  const formRules = {
    userName: [createRequiredRule('请输入用户名'), patternRules.userName],
    phone: [createRequiredRule('请输入手机号'), patternRules.phone],
    pwd: [createRequiredRule('请输入密码'), patternRules.pwd],
    code: [createRequiredRule('请输入验证码'), patternRules.code],
    email: [createRequiredRule('请输入邮箱'), patternRules.email]
  } satisfies Record<string, App.Global.FormRule[]>;

  /** 默认必填规则 */
  const defaultRequiredRule = createRequiredRule('不能为空');

  function createRequiredRule(message: string, trigger: CommonType.WithArray<string> = 'blur'): App.Global.FormRule {
    return {
      required: true,
      message,
      trigger
    };
  }

  /** 数值类型，需要添加 type: 'number' 才能正确激活 form 表单校验 */
  function createRequiredNumRule(message: string, trigger: CommonType.WithArray<string> = 'blur'): App.Global.FormRule {
    return {
      required: true,
      message,
      trigger,
      type: 'number'
    };
  }

  return {
    patternRules,
    formRules,
    defaultRequiredRule,
    ...customRules,
    createRequiredRule,
    createRequiredNumRule
  };
}

export function useNaiveForm(form = 'formRef') {
  const formRef = useTemplateRef<FormInst | null>(form);

  async function validate() {
    await formRef.value?.validate();
  }

  async function restoreValidation() {
    formRef.value?.restoreValidation();
  }

  /** 用于表单校验外部的 try catch 模块错误捕获阶段，解决未捕获错误引起的警告 */
  function catchValidateFail(error: any) {
    // eslint-disable-next-line no-console
    console.error('表单验证错误，错误信息 ->', error);
  }

  /**
   * 表单校验错误后，切换到对应的 Tab 面板中
   *
   * @param errors 表单校验错误信息
   * @param validatorTabObj tab 和 rulekey 对应关系
   * @returns tab name
   */
  function getTabPanelByError<Tabs extends string, RuleKey>(
    errors: Array<FormValidationError>,
    validatorTabObj: Record<Tabs, RuleKey[]>
  ): Tabs | '' {
    let tabName: Tabs | '' = '';
    errors.some(error => {
      /** 根据 Rulekey，在 tab 和 rulekey 对应关系中查找 Tab 面板名称 */
      const recordArray = Object.entries(validatorTabObj) as [Tabs, RuleKey[]][];
      for (const [tab, fields] of recordArray) {
        if (fields.includes(error[0].field as RuleKey)) {
          tabName = tab;
          return true;
        }
      }
      return false;
    });

    return tabName;
  }

  return {
    formRef,
    validate,
    restoreValidation,
    catchValidateFail,
    getTabPanelByError
  };
}
